package com.qiguliuxing.dts.admin.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.qiguliuxing.dts.admin.annotation.RequiresPermissionsDesc;
import com.qiguliuxing.dts.admin.service.AdminDataAuthService;
import com.qiguliuxing.dts.admin.support.AdminResponseCode;
import com.qiguliuxing.dts.admin.support.AdminResponseUtils;
import com.qiguliuxing.dts.common.constant.ApiAdminConsts;
import com.qiguliuxing.dts.common.constant.LogParamsConsts;
import com.qiguliuxing.dts.core.annotation.aoplog.WebLog;
import com.qiguliuxing.dts.core.support.JacksonUtil;
import com.qiguliuxing.dts.db.bean.CommentInfo;
import com.qiguliuxing.dts.db.bean.Commenter;
import com.qiguliuxing.dts.db.bean.UserVo;
import com.qiguliuxing.dts.db.domain.DtsGoods;
import com.qiguliuxing.dts.db.domain.DtsUser;
import com.qiguliuxing.dts.service.base.DtsCommentService;
import com.qiguliuxing.dts.service.base.DtsGoodsService;
import com.qiguliuxing.dts.service.base.DtsUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.qiguliuxing.dts.admin.support.AuthSupport;
import com.qiguliuxing.dts.common.util.ResponseUtils;
import com.qiguliuxing.dts.core.validator.Order;
import com.qiguliuxing.dts.core.validator.Sort;
import com.qiguliuxing.dts.db.domain.DtsComment;

@RestController
@RequestMapping("/admin/comment")
@Validated
@Api(tags = ApiAdminConsts.Comment.PARENT)
public class AdminCommentController {
	private static final Logger logger = LoggerFactory.getLogger(AdminCommentController.class);

	@Autowired
	private DtsCommentService commentService;

	@Autowired
	private DtsUserService dtsUserService;

	@Autowired
	private DtsGoodsService dtsGoodsService;

	@Autowired
	private AdminDataAuthService adminDataAuthService;

	@RequiresPermissions("admin:comment:list")
	@RequiresPermissionsDesc(menu = { "商品管理", "评论管理" }, button = "查询")
	@ApiOperation(value = ApiAdminConsts.Comment.LIST)
	@GetMapping("/list")
	@WebLog(description = ApiAdminConsts.Comment.LIST, excludes = {LogParamsConsts.RESPONSE})
	public Object list(
			@ApiParam(value = "用户昵称") String nickname,
			@ApiParam(value = "商品编号") String goodsSn,
			@ApiParam(value = "商品名称") String goodsName,
			@ApiParam(value = "页码",defaultValue = "1") @RequestParam(defaultValue = "1") Integer page,
			@ApiParam(value = "分页大小",defaultValue = "10") @RequestParam(defaultValue = "10") Integer limit,
			@ApiParam(value = "排序字段",defaultValue = "add_time") @Sort @RequestParam(defaultValue = "add_time") String sort,
			@ApiParam(value = "排序规则",defaultValue = "desc") @Order @RequestParam(defaultValue = "desc") String order) {
		// 需要区分数据权限，如果属于品牌商管理员，则需要获取当前用户管理品牌店铺
		List<Integer> brandIds = null;
		if (adminDataAuthService.isBrandManager()) {
			brandIds = adminDataAuthService.getBrandIds();
			logger.info("运营商管理角色操作，需控制数据权限，brandIds:{}", JSONObject.toJSONString(brandIds));

			if (brandIds == null || brandIds.size() == 0) {// 如果尚未管理任何入驻店铺，则返回空数据
				Map<String, Object> data = new HashMap<>();
				data.put("total", 0L);
				data.put("items", null);

				logger.info("【请求结束】商品管理->评论管理->查询:{}", JSONObject.toJSONString(data));
				return ResponseUtils.ok(data);
			}
		}
		List<CommentInfo> commentList = null;
		long total = 0L;
		commentList = commentService.queryBrandCommentSelective(brandIds, nickname, goodsName,goodsSn, page, limit, sort, order,null);
		if(!commentList.isEmpty()){
			for(CommentInfo commentInfo:commentList){
				commentInfo.setUserVo(dtsUserService.findUserVoById(commentInfo.getUserId()));
				commentInfo.setDtsGoods(dtsGoodsService.findById(commentInfo.getValueId()));
			}
		}
		total = PageInfo.of(commentList).getTotal();
		Map<String, Object> data = new HashMap<>();
		data.put("total", total);
		data.put("items", commentList);
		return ResponseUtils.ok(data);
	}

	@RequiresPermissions("admin:comment:delete")
	@RequiresPermissionsDesc(menu = { "商品管理", "评论管理" }, button = "删除")
	@ApiOperation(value = ApiAdminConsts.Comment.DELETE)
	@PostMapping("/delete")
	@WebLog(description = ApiAdminConsts.Comment.DELETE, persistence = true)
	public Object delete(@RequestBody DtsComment comment) {
		Integer id = comment.getId();
		if (id == null) {
			return ResponseUtils.badArgument();
		}
		commentService.deleteById(id);
		return ResponseUtils.ok();
	}

	@PostMapping("/selected")
	public Object selected(@RequestBody DtsComment comment) {
		Integer[] id = comment.getIds();
		if (id == null) {
			return ResponseUtils.badArgument();
		}
		if (comment.getIsSelected() == null) {
			return ResponseUtils.badArgument();
		}
		for(Integer queryId:id){
			DtsComment data=new DtsComment();
			data.setId(queryId);
			data.setIsSelected(comment.getIsSelected());
			commentService.update(data);
		}
		return ResponseUtils.ok();
	}

	/**
	 * 回复查询
	 *
	 * @param body 商品管理，{ orderId：xxx }
	 * @return 评论回复结果
	 */
	@RequiresPermissions("admin:comment:queryReply")
	@RequiresPermissionsDesc(menu = { "商品管理", "评论管理" }, button = "回复查询")
	@ApiOperation(value = ApiAdminConsts.Comment.QUERY_REPLY)
	@PostMapping("/queryReply")
	@WebLog(description = ApiAdminConsts.Comment.QUERY_REPLY)
	public Object queryReply(@RequestBody String body) {
		Integer commentId = JacksonUtil.parseInteger(body, "id");
		if (commentId == null || commentId == 0) {
			return ResponseUtils.badArgument();
		}

		DtsComment oldComment = commentService.findById(commentId);
		if (oldComment == null) {
			return ResponseUtils.badArgumentValue();
		}

		List<Commenter> repliers = commentService.queryAdminReply(oldComment.getId(), oldComment.getValueId());
		return ResponseUtils.ok(repliers);
	}

	/**
	 * 评论回复
	 *
	 * @param body 商品管理，{ orderId：xxx }
	 * @return 评论回复结果
	 */
	@RequiresPermissions("admin:comment:reply")
	@RequiresPermissionsDesc(menu = { "商品管理", "评论管理" }, button = "评论回复")
	@ApiOperation(value = ApiAdminConsts.Comment.REPLY)
	@PostMapping("/reply")
	@WebLog(description = ApiAdminConsts.Comment.REPLY)
	public Object reply(@RequestBody String body) {
		Integer commentId = JacksonUtil.parseInteger(body, "commentId");
		if (commentId == null || commentId == 0) {
			return ResponseUtils.badArgument();
		}
		String content = JacksonUtil.parseString(body, "content");
		if (StringUtils.isEmpty(content)) {
			return ResponseUtils.badArgument();
		}

		DtsComment oldComment = commentService.findById(commentId);
		if (oldComment == null) {
			return ResponseUtils.badArgumentValue();
		} else if (oldComment.getAdminId().intValue() == AuthSupport.adminId().intValue()) {
			logger.error("【请求结束】商场管理->订单管理->订单商品回复,操作异常:{}", AdminResponseCode.NOT_ALLOW_REPLY_SELF.desc());
			return AdminResponseUtils.fail(AdminResponseCode.NOT_ALLOW_REPLY_SELF);
		}
		commentService.reply(AuthSupport.adminId(), commentId, content, oldComment);
		return ResponseUtils.ok();
	}
}
